// 过程监督弹窗
<template>
  <div class="addDialog">
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="1200px" @close="handleClosed" :close-on-click-modal="false">
      <div class="dialogWrap">
        <el-form ref="dialogForm" :rules="type == 'approval' ? approvalRules: rules" :model="formData">
          <el-col :span="24">
            <h4 class="dialogItemTitle">装修申请上报信息</h4>
          </el-col>
          <el-row :gutter="40">
            <el-col :span="12">
              <el-form-item label="上报人" class="full" prop="initiator">
                <el-input v-model="formData.initiator" maxlength="20" :readonly="isReadonly" placeholder="请输入上报人" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="上报时间" class="full" prop="initiateTime">
                <el-date-picker
                  v-model="formData.initiateTime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  type="datetime"
                  placeholder="请选择上报时间"
                  :readonly="isReadonly"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="物业名称" prop="propertyName" class="listFormItem">
                <el-button class="add" type="primary" size="mini" @click="$refs.propertyChoose.show()" v-if="type == 'add'">选择物业</el-button>
                <el-input v-model="formData.propertyName" readonly placeholder="请输入内容" />
              </el-form-item>
            </el-col>
						<el-col :span="12">
              <el-form-item label="工程名称" class="full" prop="engineeringName">
                <el-input v-model="formData.engineeringName" :readonly="isReadonly" maxlength="100" placeholder="请输入工程名称" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="装修说明" class="full" prop="problemDesc">
                <el-input
                  v-model="formData.problemDesc"
                  type="textarea"
                  :readonly="isReadonly"
                  placeholder="请输入内容"
                   maxlength="200"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注" class="full" prop="remarks">
                <el-input
                  v-model="formData.remarks"
                  type="textarea"
                  :readonly="isReadonly"
                  :placeholder="isReadonly ? '暂无内容' : '请输入内容'"
                   maxlength="200"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 附件 -->
          <el-row :gutter="20" class="album" v-if="dialogVisible">
            <el-col :span="24">
              <h4 class="dialogItemTitle">上传附件</h4>
            </el-col>
            <el-col :span="24">
              <v-upload
                ref="upload"
                :busId="formData.billId"
                modelType="decorateQuestion"
                @onSuccess="onSuccess"
                v-model="uploadFileList"
                isShowFileList
                :isView="['preview','approval'].includes(type)"
                :autoLoadFiles="false"
              />
            </el-col>
          </el-row>

          <!-- 审批 -->
          <el-row v-if="type === 'approval'">
						<el-col :span="24">
              <h4 class="dialogItemTitle">修缮审批</h4>
            </el-col>
            <el-col :span="12">
              <el-form-item label="审批结果" class="full" prop="result">
                <el-radio-group v-model="formData.result">
                  <el-radio label="1">同意</el-radio>
                  <el-radio label="0">不同意</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
						<el-col :span="24">
							<el-form-item label="审批意见" class="full" prop="approveContent">
                <el-input v-model="formData.approveContent" type="textarea" placeholder="请输入内容"/>
              </el-form-item>
						</el-col>
          </el-row>
          <!-- 审批查看 -->
          <el-table :data="approvalList"  style="width: 100%" v-if="type === 'preview'">
            <el-table-column align="center" prop="approvePerson" label="审批人" width="160"/>
            <el-table-column prop="approveTm" label="审批时间" width="160"/>
            <el-table-column align="center" label="审批结果" width="160">
              <template slot-scope="scope">
                {{getStatusName(scope.row.approveStatus)}}
              </template>
            </el-table-column>
            <el-table-column align="center" prop="approveContent" label="审批意见"/>
          </el-table>

        </el-form>

        <!-- 物业选择弹窗 -->
        <propertyChooseDialog ref="propertyChoose" dialogType="question" @changeProperty="handlePropertyChange" />
      </div>
      <div slot="footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button  v-if="type !== 'preview'" type="primary" v-throttle="[save]">{{type == 'approval' ? '审 批':'提 交'}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import propertyChooseDialog from "@/views/wy-operate/components/propertyChooseDialog";
import uploadMedia from '@/components/upload-media';
import moment from 'moment';

import { changeDecorationApply, getApproveInfo, approvalDecoration } from "@/views/wy-operate/api/decorate.js";
export default {
  name: "addDepartment",
  components: {
    propertyChooseDialog,
    uploadMedia
	},
	inject: ['initList'],
  data() {
    return {
      //弹窗类型，默认新增
      type: "add",
      //选中的物业
      radioId: "",
      //弹窗开关
      dialogVisible: false,
      // 表单项
      formData: {
        billId: "",
        // 房源ID
        roomId: "",
        // 上报人
        initiator: "",
        // 上报时间
        initiateTime: "",
        // 物业名称
				propertyName: "",
				// 工程名称
				engineeringName: "",
        // 问题描述
        problemDesc: "",
        // 备注
        remarks: "",
        // 物业类型
				propertyType: '',
				// 平台	 10 苹果 11 安卓 13 其他
				mobileDevice: '13'
			},
			// 审批表单
			approvalForm: {
				// 审批结果
				result: "",
				// 审批内容
				approveContent: "",
				// 审批人
				approvePerson: "",
				// 审批时间
        approveTm: "",
      },
      // 审批记录
      approvalList: [],
      // 校验规则
      rules: {
        initiator: [{ required: true, message: "上报人不能为空", trigger: "blur" }],
        initiateTime: [{ required: true, message: "上报时间不能为空", trigger: "blur" }],
        propertyName: [{ required: true, message: "物业名称不能为空", trigger: "blur" }],
        engineeringName: [{ required: true, message: "工程名称不能为空", trigger: "blur" },
                        { min: 1, max: 25, message: '长度在 1 到 25 个字符', trigger: 'blur' }],
      },
      // 审批校验
      approvalRules: {
        result: [{ required: true, message: "审批结果不能为空", trigger: "blur" }],
        approveContent: [{ required: true, message: "审批意见不能为空", trigger: "blur" },
                { min: 1, max: 64, message: '长度在 1 到 64 个字符', trigger: 'blur' } ],
      },
      // 上传文件列表
      uploadFileList: [],
    };
  },
  computed: {
    // 弹窗标题计算
    dialogTitle() {
      return {
        preview: "查看",
        edit: "编辑",
        add: "新增",
        approval: "审批",
      }[this.type];
    },
    // 判断是否只读
    isReadonly() {
      return ["preview", "approval"].includes(this.type);
    },
  },
  methods: {
    //开启弹窗
    show({ type, data = {} }) {
      if(['preview','edit','approval'].includes(type)) {
        this.formData = type === 'approval' ? {...this.formData, ...this.approvalForm, ...data} : {...this.formData, ...data};
        this.$nextTick(() => {
          this.$refs.upload && this.$refs.upload.getFiles(data.billId)
        })
        // 预览状态下获取审批结果信息
        data.billStatus && this.getStatus(data.billId)
      }
      this.type = type;
			this.dialogVisible = true;
    },
		// 获取审批相关信息
		getStatus(billId) {
			getApproveInfo(billId).then(res => {
        const { records } = res.data.data
        if(records.length) {
          this.approvalForm = {
            ...records[0],
            result: this.formData.billStatus == 11 ? '1': '0'
          }
          this.approvalList = records
        }
			})
		},
    // 提交新增审批
    save() {
			if (this.type === 'approval') {
        this.$refs.dialogForm.validate((valid) => {
          if(valid){
            let { result, approveContent, approvePerson } = this.formData;
            let params = {
              approveContent,
              approvePerson,
              approveTm: moment().format('YYYY-MM-DD hh:mm:ss'),
              billId: this.formData.billId,
            }

            approvalDecoration(params, result).then((res) => {
              if(res.data.code == 0) {
                this.$message.success(`${this.dialogTitle}成功!`);
                this.initList({ current: 1, keyword: '' });
                this.dialogVisible = false;
              } else {
                this.$message.error(res.data.msg)
              }
            });
          }
        })
      }

      if(['edit','add'].includes(this.type)) {
        this.$refs.dialogForm.validate((valid) => {
          if (valid) {
            if(this.uploadFileList.length) {
              this.$refs.upload.submit('decorateQuestion',this.formData.billId);
            } else {
              changeDecorationApply(this.formData, this.type).then(res => {
                if(res.data.code == 0) {
                  this.$message.success(`${this.dialogTitle}成功!`);
                  this.initList({ current: 1, keyword: '' });
                  this.dialogVisible = false;
                } else {
                  this.$message.error(res.data.msg)
                }
              })
            }
          }
        });
      }
    },
    // 上传成功
    async onSuccess(response, file, fileList) {
      let params = this.type == 'add' ? {...this.formData, billId: response.data} : this.formData
      const res = await changeDecorationApply(params, this.type)
      if(res.data.code == 0) {
        this.$message.success(`${this.dialogTitle}成功!`);
        this.initList({ current: 1, keyword: '' });
        this.dialogVisible = false;
      } else {
        this.$message.error(res.data.msg)
      }
    },
    // 监听物业改变
    handlePropertyChange(data) {
      this.formData = {
        ...this.formData,
        address: data.address,
        propertyName: data.propertyName,
        roomId: data.roomId,
        propertyType: data.propertyType
      };
    },
    // 获取审批状态名称
    getStatusName(status = this.formData.billId) {
      return {
        '10': '待审核',
        '11': '待审核',
        '12': '审核通过',
        '13': '待验收',
        '14': '验收通过',
        '15': '验收未通过'
      }[status] || ''
    },
    // 弹窗关闭还原
    handleClosed() {
      this.uploadFileList.length = 0
      for(var i in this.formData) {
        this.formData[i] = ''
      }
      for(var i in this.approvalForm) {
        this.approvalForm[i] = ''
      }
      this.approvalList.length = 0
    }
  },
};
</script>

<style lang="scss" scoped>
@import "src/views/wy-operate/css/operate.scss";
.addDialog {
  /deep/ .el-date-editor--datetime {
    width: 100%;
  }
  .album {
    .el-col {
      margin-bottom: 20px;
    }
    .img {
      width: 100%;
      height: 200px;
    }
  }
}
</style>
